package com.learn.demo.email;

import com.learn.demo.entity.User;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.internet.MimeMessage;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Freemarker渲染邮件
 *
 * @author banjiawei
 * @date 2021/06/23
 */
@RestController
public class FreemarkerMailController {

    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String username;

    @RequestMapping("/fk/sendFreemarkerMail")
    public void sendFreemarkerMail() throws Exception {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true, "utf-8");
        helper.setSubject("这是一封freemaker渲染的测试邮件");
        helper.setFrom(username);
        List<String> stringList = Arrays.asList("2221512643@qq.com", "331939299@qq.com");
        String[] strings = new String[stringList.size()];
        stringList.toArray(strings);
        helper.setTo(strings);
//        helper.setCc("37xxxxx37@qq.com");
//        helper.setBcc("14xxxxx098@qq.com");
        helper.setSentDate(new Date());
        //构建 Freemarker 的基本配置
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_0);
        // 配置模板位置
        ClassLoader loader = FreemarkerMailController.class.getClassLoader();
        configuration.setClassLoaderForTemplateLoading(loader, "templates");
        //加载模板
        Template template = configuration.getTemplate("mail.ftl");
        User user = new User();
        user.setName("百姓关注");
        user.setAge(18);
        user.setPhone("13984842424");
        StringWriter out = new StringWriter();
        //模板渲染，渲染的结果将被保存到 out 中 ，将out 中的 html 字符串发送即可
        template.process(user, out);
        helper.setText(out.toString(),true);
        javaMailSender.send(mimeMessage);
    }
}
